// #include"http.hpp"
// #include<vector>
// #include <unistd.h>	
// #include<string>

// // void GetCwd(){
// //     char path[256];
// //     if(!getcwd(path,255)){
// //         std::cout<<"Get path fail!"<<std::endl;
// //     }
// //     std::cout<<"path:"<<path<<std::endl;
// // }


// int main(){
//     // std::vector<std::string> v1;
//     // Util::Split("ad,af,fa,cv,,123","123",&v1);
//     // for(std::string str:v1){
//     //     std::cout<<str<<std::endl;
//     // }

//     // GetCwd();
//     // std::string buf;
//     // Util::ReadFile("http.hpp",&buf);
//     // std::cout<<buf<<std::endl;

//     // std::string buf("fafafa\n fafa\n");
//     // Util::WriteFile("txt.txt",buf);
//     // std::cout<<buf<<std::endl;
    
//     // std::cout<<Util::UrlEncode("C++",false)<<std::endl;
//     // std::cout<<Util::UrlEncode("C  ",true)<<std::endl;

//     // std::cout<< Util::UrlDecode("c++21....___---",false)<<std::endl;
//     // std::cout<< Util::UrlDecode("c++21",true)<<std::endl;
//     // std::cout<< Util::UrlDecode("%23",false)<<std::endl;
    
    
//     // std::cout<< Util::StatuDesc("shabi.pptx")<<std::endl;
//     // std::cout<< Util::StatuDesc("shabi.docx")<<std::endl;

//     // std::cout<< Util::ValidPath("http/fa")<<std::endl;
//     // std::cout<< Util::IsRegular("http.hpp")<<std::endl;
//     // std::cout<< Util::IsDirectory("./fa")<<std::endl;//work_director是http里面

//     return 0;
// }


#include"http.hpp"
#include <iostream>
#include <mysql/mysql.h>
#include <string>
const std::string DB_HOST = "localhost";//从本地host登录，但是对用户的设置可以规定不同的host登录一个是设置，一个是登录地址
const size_t PORT = 3306;
const std::string DB_USER = "zhaoguang";
const std::string DB_PASS = "497380411zg.";
const std::string DB_NAME = "TcpServerdb";

// 检查表是否存在
bool tableExists(MYSQL* conn, const std::string& tableName) {
    std::string query = "SHOW TABLES LIKE '" + tableName + "'";
    if (mysql_query(conn, query.c_str())) {
        std::cerr << "Error executing query: " << mysql_error(conn) << std::endl;
        return false;
    }

    MYSQL_RES* result = mysql_store_result(conn);
    if (!result) {
        std::cerr << "Error storing result: " << mysql_error(conn) << std::endl;
        return false;
    }

    bool exists = (mysql_num_rows(result) > 0);
    mysql_free_result(result);
    return exists;
}

// 创建 User 表
bool createUserTable(MYSQL* conn) {
    std::string query = R"(
        CREATE TABLE User (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(50) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL
        )
    )";

    if (mysql_query(conn, query.c_str())) {
        std::cerr << "Error creating table: " << mysql_error(conn) << std::endl;
        return false;
    }
    return true;
}

// 插入用户名和密码
bool insertUser(MYSQL* conn, const std::string& name, const std::string& password) {
    std::string query = "INSERT INTO User (name, password) VALUES ('" + name + "', '" + password + "')";
    if (mysql_query(conn, query.c_str())) {
        std::cerr << "Error inserting user: " << mysql_error(conn) << std::endl;
        return false;
    }
    return true;
}

bool InsertUserData(const std::string &name,const std::string& password){
    MYSQL* conn = mysql_init(nullptr);
    if (!conn) {
        std::cerr << "mysql_init() failed" << std::endl;
        return EXIT_FAILURE;
    }
    // 连接到 MySQL 数据库
    if (!mysql_real_connect(conn, DB_HOST.c_str(), DB_USER.c_str(), DB_PASS.c_str(), DB_NAME.c_str(), PORT, nullptr, 0)) {
        std::cerr << "mysql_real_connect() failed: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return EXIT_FAILURE;
    }
    std::cout << "Connected to MySQL server." << std::endl;
    // 检查 User 表是否存在
    if(!tableExists(conn,"User")){
        std::cout << "User table does not exist. Creating it..." << std::endl;
        if (!createUserTable(conn)) {
            std::cerr << "Failed to create User table." << std::endl;
            mysql_close(conn);
            return EXIT_FAILURE;
        }
        std::cout << "User table created successfully." << std::endl;
        // 插入用户名和密码
        insertUser(conn, name,password);    
        return true;
    } else {
        std::cout << "User table already exists." << std::endl;  
        return false;   
    }  
}


#define WWWROOT "./wwwroot/"
std::string RequestStr(const HttpRequest &req){
    std::stringstream ss;  //字符串流
    ss<<req._method<<" "<<req._path<<" "<<req._version<<"\r\n";
    for(auto &it : req._params){
        ss << it.first<<": "<<it.second<<"\r\n";
    }
    for(auto &it : req._headers){
        ss << it.first <<": "<< it.second<<"\r\n";
    }
    ss<< "\r\n";
    ss<< req._body;
    return ss.str();
} 

void Hello(const HttpRequest &req, HttpResponse *rsp){
    rsp -> SetContent(RequestStr(req), "text/plain");//设置rsp._body 和其类型
    sleep(10);

}

void Login(const HttpRequest &req, HttpResponse *rsp){
    rsp -> SetContent(RequestStr(req),"text/plain");
    //拿到req的user和password,并插入到数据库
    const std::string user = req._params.at(std::string("user")); //.at()函数是const方法不会修稿const unordered_map
    const std::string password = req._params.at(std::string("password"));
    // 拿到req的user和password,并插入到数据库
    // std::vector<std::string> v;
    // Util::Split(req._path, "$",v);
    // InsertUserData(user,password);  
}

void PutFile(const HttpRequest &req, HttpResponse *rsp){
    std::string pathname = WWWROOT + req._path; 
    std::cout<<"pathname:"<<pathname<<std::endl;
    Util::WriteFile(pathname, req._body); //写入文件
}

void DelFile(const HttpRequest &req, HttpResponse *rsp){
    rsp->SetContent(RequestStr(req), "text/plain");
}

int main(){
    HttpServer server(8888);
    server.SetThreadCount(3);
    server.SetBaseDir(WWWROOT);
    server.Get("/hello",Hello);
    server.Post("/login",Login);
    server.Put("/1234.txt",PutFile);
    server.Delete("/1234.txt",DelFile);
    server.Listen();
    return 0;   
}

